import type { ModelStuck, ModelItem } from '@/types'
import { upperFirst } from 'lodash-es'
/**
 * getProtoString:生成proto描述文件
 */
export const getProtoString = (options: ModelStuck, whiteKeyList: string[]) => {
  const getProtoCreateString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['onlyId', 'editor'])
    const filterFields = options?.content.filter((item) => !newWhiteKeyList.includes(item.name))
    const fields = filterFields.map(
      (item, index) => `${item.type} ${item.name} = ${index + 1}; //${item.remark}`
    )
    const str = `message Create${options.modelName}Req {\n\n${fields.join('\n\n')}\n\n}\n\n`
    const strResp = `message Create${options.modelName}Resp {\n\n }\n\n`
    return str + strResp
  }

  const getProtoUpdateString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['creator'])
    const filterFields = options?.content.filter((item) => !newWhiteKeyList.includes(item.name))
    const fields = filterFields.map(
      (item, index) => `${item.type} ${item.name} = ${index + 1}; //${item.remark}`
    )
    const str = `message Update${options.modelName}Req {\n\n${fields.join('\n\n')}\n\n}\n\n`
    const strResp = `message Update${options.modelName}Resp {\n\n }\n\n`
    return str + strResp
  }

  const getProtoDeleteString = (options: ModelStuck) => {
    const str = `message Delete${options.modelName}Req {\n\n string onlyId = 1;//数据onlyId\n\n}\n\n`
    const strResp = `message Delete${options.modelName}Resp {\n\n }\n\n`
    return str + strResp
  }

  const getProtoQueryString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['creator', 'editor'])
    const commonFields: ModelItem[] = [
      {
        name: 'pageIndex',
        type: 'int64',
        remark: '分页页码'
      },
      {
        name: 'pageSize',
        type: 'int64',
        remark: '分页每页数量'
      }
    ]
    const filterFields = options?.content
      .filter((item) => !newWhiteKeyList.includes(item.name))
      .concat(commonFields)
    // 单个数据的item
    const itemsFiles = options?.content.map(
      (item, index) => `${item.type} ${item.name} = ${index + 1}; //${item.remark}`
    )
    // 请求结构的
    const reqFields = filterFields.map(
      (item, index) => `${item.type} ${item.name} = ${index + 1}; //${item.remark}`
    )
    const itemStr = `message ${options.modelName}Item {\n\n${itemsFiles.join('\n\n')}\n\n}\n\n`

    const queryReq = `message Get${options.modelName}ListReq {\n\n${reqFields.join('\n\n')}\n\n}\n\n`

    const queryResp = `message Get${options.modelName}ListResp {\n\nrepeated ${options.modelName}Item list = 1; // 数据列表\n\n int64 total = 2; //数据总数 \n\n}\n\n`

    return itemStr + queryReq + queryResp
  }

  const getServiceString = (options: ModelStuck) => {
    const rpcList: string[] = []
    rpcList.push(
      `rpc Create${options.modelName} (Create${options.modelName}Req) returns (Create${options.modelName}Resp); //创建`
    )
    rpcList.push(
      `rpc Update${options.modelName} (Update${options.modelName}Req) returns (Update${options.modelName}Resp); //更新`
    )
    rpcList.push(
      `rpc Delete${options.modelName} (Delete${options.modelName}Req) returns (Delete${options.modelName}Resp); //删除`
    )
    rpcList.push(
      `rpc Get${options.modelName}List(Get${options.modelName}ListReq) returns (Get${options.modelName}ListResp); //查询`
    )

    return `service ${options.modelName} {\n\n ${rpcList.join('\n\n')} \n\n}\n\n`
  }
  return (
    getProtoCreateString(options, whiteKeyList) +
    getProtoUpdateString(options, whiteKeyList) +
    getProtoDeleteString(options) +
    getProtoQueryString(options, whiteKeyList) +
    getServiceString(options)
  )
}

/**
 * getRpcString：创建的rpc代码
 */
export const getRpcCreateString = (options: ModelStuck) => {
  const createString = `
	var data model.${options.modelName}
	err = copier.Copy(&data, in)
	if err != nil {
		return nil, err
	}
	data.OnlyId = tools.GenSn()
	_, err = l.svcCtx.${options.modelName}Model.Insert(l.ctx, nil, &data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("创建失败"), "创建失败 , err:%v , ", err)
	}
	return &pb.Create${options.modelName}Resp{}, nil
  `
  return createString
}

/**
 * getRpcDeleteString:删除的rpc代码
 */
export const getRpcDeleteString = (options: ModelStuck) => {
  const deleteString = `
  err := l.svcCtx.${options.modelName}Model.Delete(l.ctx, nil, in.OnlyId)

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除失败"), "删除内容失败 , err:%v , ", err)
	}

	return &pb.Delete${options.modelName}Resp{}, nil
  `
  return deleteString
}

export const getRpcQueryString = (options: ModelStuck, whiteKeyList: string[]) => {
  const newWhiteKeyList = whiteKeyList.concat(['creator', 'editor'])
  const queryKeyList = options.content.filter((item) => !newWhiteKeyList.includes(item.name)) //不包含的
  const queryItemList = queryKeyList.map((item) => {
    if (item.type === 'string') {
      return `
      if in.${upperFirst(item.name)} != "" {
        listBuilder = listBuilder.Where(squirrel.Eq{"${item.name}": in.${upperFirst(item.name)}})
      }
    `
    } else {
      return `
      if in.${upperFirst(item.name)} > -1 {
        listBuilder = listBuilder.Where(squirrel.Eq{"${item.name}": in.${upperFirst(item.name)}})
      }
    `
    }
  })

  const queryString = `
  listBuilder := l.svcCtx.${options.modelName}Model.SelectBuilder()
	${queryItemList.join('')}

	dbList, total, err := l.svcCtx.${options.modelName}Model.FindPageListByPageWithTotal(l.ctx, listBuilder, in.PageIndex, in.PageSize, "createTime")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("查询失败"), "查询记录失败： , err:%v ", err)
	}
	var list []*pb.${options.modelName}Item
	tools.CopyListForAddrItem(&list, dbList)

	return &pb.Get${options.modelName}ListResp{
		Total: total,
		List:  list,
	}, nil
  `
  return queryString
}

/**
 * getRpcUpdateString:更新的rpc代码
 */
export const getRpcUpdateString = (options: ModelStuck) => {
  const updateString = `
  data, err := l.svcCtx.${options.modelName}Model.FindOne(l.ctx, in.OnlyId)

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新失败"), "更新失败失败，查询出错 , err:%v , ", err)
	}
	copier.Copy(&data, in)
	err = l.svcCtx.${options.modelName}Model.UpdateWithVersion(l.ctx, nil, data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新失败"), "更新失败失败 , err:%v , ", err)
	}
	return &pb.Update${options.modelName}Resp{}, nil
  `
  return updateString
}
